package utils

import (
	//"encoding/json"
	//"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/astaxie/beego/httplib"
)

func GetToken() string {
	resp, _ := http.Get("http://47.100.1.225/gettoken/")
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	token := string(body)
	return token
}

type Value struct {
	Value string `json:"value"`
	Color string `json:"color"`
}
type Data0 struct {
	Error Value `json:"error"`
	Date  Value `json:"date"`
	Stay  Value `json:"stay"`
}

type WX struct {
	Touser      string `json:"touser"`
	Template_id string `json:"template_id"`
	Url         string `json:"url"`
	Data        Data0  `json:"data"`
}

func PostError(stay, errstring string) {
	token := GetToken()

	timestamp := time.Now().Unix()
	tm := time.Unix(timestamp, 0)

	body := WX{
		Touser:      "o444o082x0HLWEz9IPWUHUV1j0Aw",
		Template_id: "yDiPLKn3UwirLWBHMy8Z_0UymMo8v-w9_FX3edWhuLs",
		Url:         "http://price.liangyunli.cn/api/price/",
		Data: Data0{
			Error: Value{
				Value: errstring,
				Color: "red",
			},
			Date: Value{
				Value: tm.Format("2006-01-02 03:04:05 PM"),
				Color: "balck",
			},
			Stay: Value{
				Value: stay,
				Color: "balck",
			},
		},
	}

	url := "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token
	post := httplib.Post(url)

	post.JSONBody(body)
	post.DoRequest()
}
